<template>
  <div class="app-container">
    <el-row :gutter="24" class="mb8">
      <el-col :span="4">
        <el-menu :default-active="activeMenuIndex" id="menu" mode="vertical"
                 @open="handleMenuOpen"
                 @select="handleDbSel"
        >
          <SubMenu
            v-for="(firstItem, firstIndex) in menu"
            :key="firstIndex"
            :item="firstItem"
            :index="String(firstIndex)"
            :level="1"
            children="childrenList"
            nameValue="typeName"
          />
        </el-menu>
        <div class="line"></div>
      </el-col>
      <el-col  :span="20">
        <!--        搜索表单-->
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="88px">
          <el-form-item label="关键词" prop="keyword">
            <el-input :model="queryParams.keyword" placeholder="请输入关键词" clearable
                      @keyup.enter.native="handleQuery"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <!--        顶部的修改，删除按钮-->
<!--        <el-row :gutter="10" class="mb8">-->
<!--          <el-col :span="1.5">-->
<!--            <el-button type="success"-->
<!--                       plain-->
<!--                       icon="el-icon-edit"-->
<!--                       size="mini"-->
<!--                       :disabled="single"-->
<!--                       @click="handleUpdate"-->
<!--                       v-hasPermi="['datasourceBase:edit']"-->
<!--            >修改-->
<!--            </el-button>-->
<!--          </el-col>-->
<!--          <el-col :span="1.5">-->
<!--            <el-button type="danger"-->
<!--                       plain-->
<!--                       icon="el-icon-delete"-->
<!--                       size="mini"-->
<!--                       :disabled="multiple"-->
<!--                       @click="handleDelete"-->
<!--                       v-hasPermi="['datasourceBase:remove']"-->
<!--            >删除-->
<!--            </el-button>-->
<!--          </el-col>-->
<!--          <right-toolbar @queryTable="getList"></right-toolbar>-->
<!--        </el-row>-->
        <!--        表格-->
        <el-table v-loading="loading" :data="databaseList" @selection-change="handleSelectionChange">
<!--          <el-table-column type="selection" width="55" align="center" />-->
          <el-table-column type="index" width="50" align="center" label="序号"></el-table-column>
          <el-table-column label="资源名称" align="center" prop="dbName" width="120" />
          <el-table-column label="资源别名" align="center" prop="dbNickName" width="120" />
          <el-table-column label="资源类型" align="center" prop="dbType" width="120" />
          <el-table-column label="所在平台"
                           align="center"
                           prop="datasourceSystemName"
                           :show-overflow-tooltip="true" />
          <el-table-column label="资源数量" align="center" prop="tableNumber" />
          <el-table-column label="记录总数" align="center" prop="totalRows">
                       <template slot-scope="scope">
             {{ scope.row.totalRows===-1?'/': scope.row.totalRows}}
          </template>
          </el-table-column>
          <el-table-column label="登记时间" align="center" prop="createTime" :show-overflow-tooltip="true" />
          <el-table-column label="资源url" align="center" prop="originUrl"  :show-overflow-tooltip="true" >
<!--            <template slot-scope="scope">-->
<!--              {{ scope.row.originUrl ?`${scope.row.originUrl.slice(0,10)}...`:'无' }}-->
<!--            </template>-->
          </el-table-column>
          <el-table-column label="备注" align="center" prop="remark" />
          <el-table-column label="操作"
                           align="center"
                           class-name="small-padding fixed-width"
                           fixed="right"
                           width="200">
            <template slot-scope="scope">
<!--              <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"-->
<!--                         v-hasPermi="['datasourceBase:edit']"-->
<!--              >修改-->
<!--              </el-button>-->
<!--              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"-->
<!--                         v-hasPermi="['datasourceBase:remove']"-->
<!--              >删除-->
<!--              </el-button>-->
              <el-button size="mini" type="text" icon="el-icon-more-outline" @click="handleDetail(scope.row)"
                         v-hasPermi="['datasourceBase:remove']"
              >详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="databaseTotal>0" :total="databaseTotal" :page.sync="queryParams.currPage"
                    :limit.sync="queryParams.pageSize" @pagination="getList"
        />
        <!--    修改弹窗-->
        <el-dialog :title="UpdateTitle" :visible.sync="UpdateOpen" width="80%" append-to-body>
          <el-form :model="databaseForm" label-width="120px" :rules="databaseRule" ref="databaseForm">
            <el-row>
              <el-col :span="12">
                <el-form-item label="资源名称" prop="dbName" required>
                  <el-input placeholder="请输入资源名称" v-model="databaseForm.dbName" disabled></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="资源别名" prop="dbNickName">
                  <el-input placeholder="请输入资源别名" v-model="databaseForm.dbNickName"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="资源类型" prop="dbType">
                  <el-input placeholder="请输入资源别名" v-model="databaseForm.dbType" disabled></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="前导库" prop="originDatasourceDbIdList">
                  <el-select
                    v-model="originDatasourceDbIdList"
                    multiple
                    filterable
                    remote
                    reserve-keyword
                    placeholder="请输入关键词进行选择"
                    :remote-method="dbRemoteMethod"
                    :loading="dbLoading"
                  >
                    <el-option
                      v-for="item in dbOptions"
                      :key="item.id"
                      :label="item.dbName"
                      :value="item.id"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="所在平台" prop="datasourceSystemId">
                  <el-select
                    v-model="databaseForm.datasourceSystemId"
                    filterable
                    remote
                    reserve-keyword
                    placeholder="请输入关键词进行选择"
                    :remote-method="systemRemoteMethod"
                    :loading="systemLoading"
                  >
                    <el-option
                      v-for="item in systemOptions"
                      :key="item.id"
                      :label="`${item.unit}-${item.systemName}`"
                      :value="item.id"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="所属分类" prop="typeIdList">
                  <el-cascader
                    :props="typeProps"
                    :options="typeOptions"
                    ref="cascader"
                    filterable
                    clearable
                    :show-all-levels="false"
                    :collapse-tags="true"
                    @change="getCheckedNodes"
                    v-model="databaseForm.typeIdList"
                  ></el-cascader>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-form-item label="数据资源文件" prop="originUrl">
                <el-upload
                  class="upload-demo"
                  action=""
                  :multiple=false
                  :before-upload="handleFileUpload"
                  list-type="text"
                  v-model="databaseForm.originUrl"
                >
                  <el-button size="small" type="primary">点击上传</el-button>
                </el-upload>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item label="备注" prop="remark" >
                <el-input v-model="databaseForm.remark"
                          placeholder="请输入详细介绍"
                          type="textarea"
                          maxlength="1000"
                          show-word-limit
                />
              </el-form-item>
            </el-row>
          </el-form>
          <div slot="footer" class="dialog-footer" prop="status">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </el-dialog>

        <!--        详情弹窗-->
        <el-dialog :title="DetailTitle" :visible.sync="DetailOpen" width="80%" append-to-body>
          <el-form :model="databaseForm" label-width="120px" :rules="databaseRule" ref="databaseForm">
            <el-row>
              <el-col :span="12">
                <el-form-item label="资源名称" prop="dbName" required>
                  <el-input placeholder="暂无" v-model="databaseForm.dbName" disabled></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="资源别名" prop="dbNickName">
                  <el-input placeholder="暂无" v-model="databaseForm.dbNickName" disabled></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="资源类型" prop="dbType">
                  <el-input placeholder="暂无" v-model="databaseForm.dbType" disabled></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="所在平台" prop="datasourceSystemName">
                  <el-input placeholder="暂无"
                            v-model="databaseForm.datasourceSystemName"
                            disabled
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="资源总数" prop="tableNumber">
                  <el-input placeholder="暂无" v-model="databaseForm.tableNumber" disabled></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="记录总数" prop="totalRows">
                  <el-input placeholder="暂无"
                            v-model="databaseForm.totalRows"
                            disabled
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="前导库" prop="originDatasourceDbIdList">
                  <el-select
                    v-model="originDatasourceDbIdList"
                    multiple
                    filterable
                    remote
                    reserve-keyword
                    placeholder="暂无"
                    :remote-method="dbRemoteMethod"
                    :loading="dbLoading"
                    disabled
                  >
                    <el-option
                      v-for="item in dbOptions"
                      :key="item.id"
                      :label="item.dbName"
                      :value="item.id"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="所属分类" prop="typeIdList" placeholder="暂无">
                  <el-cascader
                    :props="typeProps"
                    :options="typeOptions"
                    ref="cascader"
                    filterable
                    clearable
                    @change="getCheckedNodes"
                    disabled
                    v-model="databaseForm.typeIdList"
                  ></el-cascader>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-form-item label="资源url" prop="originUrl">
                <el-input placeholder="暂无"
                          v-model="databaseForm.originUrl"
                          disabled
                          type="textarea"
                ></el-input>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item label="备注" prop="remark" >
                <el-input v-model="databaseForm.remark"
                          placeholder="暂无"
                          type="textarea"
                          maxlength="1000"
                          show-word-limit
                          disabled
                />
              </el-form-item>
            </el-row>
            <el-row>
             <DataBaseEchart :data="dbRelationship"  :key="dbRelationshipKey"/>
            </el-row>
            <el-row>
            </el-row>
          </el-form>
        </el-dialog>
      </el-col>
    </el-row>
  </div>
</template>
<script>

import {
  databaseAll,
  databaseDel,
  databaseEdit,
  databaseList, databaseRelation,
  resourceFileUpload
} from '@/api/qysj/app/rawData/Database'
import { platformAll } from '@/api/qysj/app/rawData/platformSystem'
import DataBaseEchart from '@/views/qysj/data/raw/DataBaseEchart.vue'
import SubMenu from '@/views/qysj/data/raw/SubMenu.vue'
import { getCategoryAll } from '@/api/qysj/app/rawData/field'
import { listFieldType } from '@/api/qysj/app/FieldType'

export default {
  name: 'DataBase',
  components: { SubMenu, DataBaseEchart },
  data() {
    return {
      // 查询参数
      queryParams: {
        keyword: '',
        pageSize: 10,
        currPage: 1,
        typeId:null,//分类id
      },
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 加载表格
      loading: false,
      // 平台列表
      databaseList: [],
      // 平台总数
      databaseTotal: 0,
      // 新增表单标题
      UpdateTitle: '',
      // 弹出框状态
      UpdateOpen: false,
      // 详情表单标题
      DetailTitle: '',
      DetailOpen: false,
      // 资源表单
      databaseForm: {
        dbType: [] ,// 选中的资源类型
        originDatasourceDbIdList:[]
      },
      // 前导数据库id
      originDatasourceDbIdList:[],
      // 数据通道类型列表
      dataBaseTypeList: [],
      // // 选中的数据类型
      // dbType:[],

      // 表单校验
      databaseRule: {
        dbName: [
          { required: true, message: '请输入资源名称', trigger: 'blur' }
        ],
        // remark: [
        //   { required: true, message: '请输入备注信息', trigger: 'blur' }
        // ]
      },
      // 前导库多选框相关
      systemOptions: [],
      dbValue: [],
      list: [],
      dbLoading: false,
      selIds: [],
      // 平台选择框
      systemValue: null,
      dbOptions: [],
      systemLoading: false,
      // 资源关系
      dbRelationship:null,
      dbRelationshipKey: 0, // 添加一个用于触发重新渲染的 key
      // 当前选中目录
      activeMenuIndex:'',
      // 目录
      menu:[],
      // 分类级联选择器
      typeProps: {
        lazy: false,
        multiple: true ,
        clearable:true,
        emitPath:false,
        // lazyLoad(node, resolve) {
        //   console.log('node', node.value)
        //   getCategoryAll({
        //     keyword: null,
        //     parentId:node.value||null,
        //   }).then(res=>{
        //     if (res.code===200){
        //       console.log('res.data', res.data)
        //       const nodes=res.data.map(item=>{
        //         return {
        //           value: item.id,
        //           label:item.typeName,
        //           leaf: !(item.level<8)
        //         }
        //       });
        //       console.log('nodes', nodes)
        //       resolve(nodes)
        //     }
        //   })
        // }
      },
      // 分类数组
      typeOptions:[]
    }

  },
  created() {
    this.getList()
    this.startTimer()
    this.getMenuList()
  },
  watch: {
    DetailOpen(newValue) {
      if (newValue) {
        // 当弹窗打开时，更新 dbRelationshipKey，触发重新渲染
        this.dbRelationshipKey += 1;
      }
    },
    watch: {
      'databaseForm.originDatasourceDbIdList': {
        handler(newValue, oldValue) {
          // 执行你的逻辑，例如更新其他数据
          console.log('newValue', newValue)
          console.log('oldValue', oldValue)
        },
        deep: true // 监听对象的属性变化
      }
    },
  },

  methods: {
    // 开始定时器
    startTimer() {
      this.timerId = setInterval(() => {
        // 在这里执行定时要执行的操作，例如重新加载数据
        this.getList();
      }, 3*60*1000); //三分钟定时刷新一次
    },
    // 停止定时器
    stopTimer() {
      clearInterval(this.timerId);
    },
    // 获取列表
    getList() {
      this.loading=true;
      databaseList(this.queryParams).then(res => {
        if (res.code === 200) {
          if (res.rows){
            this.databaseList = res.rows
            this.databaseTotal = res.total
            this.loading=false;
          }else if (res.rows===null){
            this.databaseList=[]
            this.loading=false;
          }
        }else if (res.code===0){
          this.databaseList=[]
          this.loading=false;
        }
        else {
          this.$message(res.msg)
        }
      })
    },
    getMenuList(){
      getCategoryAll().then(res=>{
        if (res.code===200){
          this.menu=res.data;
          const propertyMap={
            'childrenList':'children',
            'id':'value',
            'typeName':"label"
          }
          console.log('this.menu', this.menu)
          this.typeOptions = JSON.parse(JSON.stringify(res.data)); // 进行深拷贝
          // this.typeOptions=res.data
          this.typeOptions.forEach((item,index)=>this.renameProperties(item,propertyMap))
        }else {
          this.$message(res.msg)
        }
      })
    },
    handleMenuOpen(index){
      // const arr = index.split('-').map(Number);
      let currentMenu=this.getCurrentMenu(index);
      this.queryParams.typeId=currentMenu.id;
      this.getList()
    },
    handleDbSel(index){
      let currentMenu=this.getCurrentMenu(index);
      this.queryParams.typeId=currentMenu.id;
      this.getList()
    },
    // 根据index路径获取当前的目录对象
    getCurrentMenu(index){
      const arr = index.split('-').map(Number);
      let currentMenu=null;
      for (let i=0;i<arr.length;i++){
        if (i===0){
          currentMenu=this.menu[arr[i]]
        }else {
          if (currentMenu&&currentMenu.childrenList&&currentMenu.childrenList.length>0){
            currentMenu=currentMenu.childrenList[arr[i]]
          }
        }
      }
      return currentMenu;
    },
    // 多选框处理
    handleSelectionChange(selection) {
      this.selIds = selection.map((item) => item.id)
      // console.log('selItems', this.selIds,this.selIds.join(','))
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    // 搜索按钮
    handleQuery() {
      this.queryParams.pageNum = 1
      this.queryParams.typeId=null
      this.getList()
    },
    // 重置按钮
    resetQuery() {
      this.resetForm('queryForm')//全局方法
      this.handleQuery()
    },
    //新增按钮
    handleAdd() {
      this.UpdateOpen = true
      this.UpdateTitle = '新增资源信息'
    },
    // 修改按钮
    handleUpdate(data) {
      this.UpdateTitle = '修改资源信息'
      this.databaseForm = data;
      this.systemOptions =[data.datasourceSystem]
      this.databaseForm.datasourceSystemId=Number(data.datasourceSystemId)
      this.dbOptions=data.originDbList;
      this.originDatasourceDbIdList=data.originDbList?.map(item=>(item.id))
      this.UpdateOpen = true
    },
    // 删除按钮
    handleDelete(data) {
      const ids = data.id || this.selIds
      databaseDel(ids).then(res => {
        if (res.code) {
          this.$message('删除成功')
          this.getList()
        } else {
          this.$message(res.msg)
        }
      })
    },
    handleDetail(data) {
      this.databaseForm = data;
      this.dbOptions=data.originDbList;
      this.originDatasourceDbIdList=data.originDbList?.map(item=>(item.id))
      this.DetailTitle = '资源详情'
      databaseRelation(data.id).then(res=>{
        if (res.code===200){
          this.dbRelationship=res.data;
          this.dbRelationship.currentDb=data;
          console.log('父组件',  this.dbRelationship)
          this.DetailOpen = true
        }else {
          this.$message(res.msg)
        }
      })
    },
    getCheckedNodes(){
      let nodesInfo = this.$refs['cascader'].getCheckedNodes(true).map(item=>item.value);
      console.log('nodesInfo', nodesInfo)
      this.databaseForm.typeIdList=nodesInfo
    },
    // 弹出框提交按钮
    submitForm() {
      this.databaseForm.originDatasourceDbIdList=this.originDatasourceDbIdList
      this.$refs['databaseForm'].validate((vaild) => {
        if (vaild) {
          databaseEdit(JSON.stringify(this.databaseForm)).then(res => {
            if (res.code === 200) {
              this.$message('修改成功')
              this.$refs['databaseForm'].resetFields()
              this.UpdateOpen = false
              this.getList()
            } else {
              this.$message(res.msg)
            }
          })
        }
      })
    },
    // 弹出框取消
    cancel() {
      this.$refs['databaseForm'].resetFields()
    },
    // 级联选择器更改属性名
    renameProperties(obj, propertyMap) {
      for (let key in obj) {
        if (obj[key] && typeof obj[key] === 'object') {
          this.renameProperties(obj[key], propertyMap);
        }
        if (propertyMap[key]) {
          obj[propertyMap[key]] = obj[key];
          delete obj[key];
        }
      }
    },
    // 前导库多选框
    dbRemoteMethod(query) {
      if (query !== '') {
        this.dbLoading = true
        databaseAll({ keyword: query }).then(res => {
          if (res.code === 200) {
            this.dbLoading = false
            this.dbOptions = res.data
            console.log(' this.dbOptions',  this.dbOptions)
          } else {
            this.dbOptions = []
            this.$message(res.msg)
          }
        })
      } else {
        this.dbOptions = []
      }
    },
    systemRemoteMethod(query) {
      if (query !== '') {
        this.systemLoading = true
        platformAll({ keyword: query }).then(res => {
          if (res.code === 200) {
            this.systemLoading = false
            this.systemOptions = res.data
          } else {
            this.systemOptions = []
            this.$message(res.msg)
          }
        })
      } else {
        this.systemOptions = []
      }
    },
    // 资源文件上传
    handleFileUpload(file) {
      const form = new FormData()
      form.append('file', file)
      resourceFileUpload(form).then(res => {
        if (res.code === 200) {
          this.databaseForm.originUrl = res.url
          this.$message('上传成功')
        } else {
          this.$message(res.msg)
        }
      })
    }
  },
  beforeDestroy() {
    // 在组件销毁前，停止定时器以防止内存泄漏
    this.stopTimer();
  },
}

</script>
